<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-08-19
 * Time: 23:19
 */
namespace app\wxapi\controller;

use app\common\controller\Wxapibase;
use app\common\model\Comment;
use app\common\model\Order as cxModel;

class Order extends Wxapibase {

    public function index(){
        if(request()->isPost()){
            $cxmodel = new cxModel();
            $data = input('post.');
            $data = datatrim($data);
            $old = $cxmodel->where('aid',$data['aid'])->where('uid',$this->cxbsuser['uid'])->count();
            if($old > 0){
                $this->error("您已参团，请勿重复报名！",url('part/index',array('fid'=>'3')));
            }
            //  获取用户信息
            $userdata = model('UserApi')->where('openid',$this->wxuser['openid'])->find();
            $userconf = unserialize($userdata['conf']);
            $data['nickname'] = $userconf['nickname'];
            $data['usertoken'] = $this->wxuser['openid'];
            $data['sex'] = $userconf['sex'];
            //  获取产品信息
            $article = $this->get_shop($data['aid']);
            if(!empty($article['picurl'])){
                $data['picurl'] = $article['picurl'];
            }elseif(!empty($article['pinimg'])){
                $data['picurl'] = $article['pinimg'];
            }else{
                $data['picurl'] = $article['paid']['0']['picurl'];
            }
            //  查询其他团购人员
            $foid = $cxmodel->where('aid',$article['aid'])->where('foid','0')->value('oid');
            if(empty($foid)){
                $foid = '0';
            }
            //  查询订单
            $oid = 'PTG'.date("Ymd").$this->addoid();
            if(empty($data['foid'])){
                $data['foid'] = '0';
            }
            $data['pricemoney'] = $article['pinmoney'];
            if($article['pinclass'] == '0元团'){
                $data['pricemoney'] = '0';
            }
            $data['pricemoney'] = bcmul($data['pricemoney'],'100');
            $data['mid'] = $article['mid'];
            $data['rennum'] = $article['rennum'];
            $order = array(
                'oid' => $oid,
                'foid' => $foid,
                'uid' => $userdata['uid'],
                'aid' => $article['aid'],
                'title' => $article['title'],
                'uphone' => $data['phone'],
                'allmoney' => $data['pricemoney'],
                'pricemoney' => $data['pricemoney'],
                'playstatus' => '0',
                'mid' => $article['mid'],
                'conf' => serialize($data),
                'addtime' => time(),
                'playtime' => '0',
            );
            if($cxmodel->allowField(true)->save($order)){
                if($article['pinclass'] == '0元团' && $article['enduser'] == '是'){
                    $enduser = json_decode($article['endusers'],true);
                    $endorder = $cxmodel->where('uid',$enduser['uid'])->where('aid',$article['aid'])->count();
                    if($endorder == '0'){
                        //  重新模拟编辑用户信息
                        $newuser = array(
                            'aid' => $article['aid'],
                            'uid' => $article['uid'],
                            'rennum' => $article['rennum'],
                            'addres' => $enduser['uaddress'],
                            'zoneid' => '',
                            'phone' => $enduser['uphone'],
                            'postal' => '',
                            'adduname' => $enduser['uname'],
                            'foid' => $oid,
                            'nickname' => $enduser['username'],
                            'usertoken' => '',
                            'sex' => $enduser['usex'],
                            'picurl' => $data['picurl'],
                            'pricemoney' => '0'
                        );
                        $this->add_auto($newuser,$oid,$article);
                    }
                }
                unset($userdata);
                unset($data);
                unset($old);
                unset($userconf);
                unset($foid);
                unset($article);
                unset($order);
                unset($enduser);
                unset($endorder);
                unset($newuser);
                $this->redirect(url('Wxpay/index',array('oid'=>$oid)),302);
            }else{
                $this->error('订单提交失败,请重试');
            }
        }
    }
    //  自动插入订单
    protected function add_auto($userdata,$oid,$data){
        // 编辑订单信息
        $order = array(
            'oid' => 'PTG'.date("Ymd").$this->addoid(),
            'foid' => $oid,
            'uid' => $userdata['uid'],
            'aid' => $data['aid'],
            'title' => $data['title'],
            'uphone' => $userdata['phone'],
            'allmoney' => '0',
            'pricemoney' => '0',
            'playstatus' => '1',
            'mid' => $data['mid'],
            'conf' => serialize($userdata),
            'addtime' => time(),
            'playtime' => time(),
        );
        $cxmodel = new cxModel();
        $cxmodel->allowField(true)->isUpdate(false)->save($order);
        unset($order);
        unset($userdata);
        unset($data);
        unset($oid);
        return true;
    }
    //  添加购物车
    public function addche(){
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            $olddata = model('OrderShop')->get_list($this->cxbsuser['uid']);
            if(empty($olddata)){
                $olddata['uid'] = $this->cxbsuser['uid'];
            }
            $newadd = true;
            $data['aid'] = explode(',',$data['aid']);
            foreach ($data['aid'] as $val){
                if(empty($val)){
                    continue;
                }
                if(!empty($olddata['aids'])){
                    foreach ($olddata['aids'] as $k => $v){
                        if($v['aid'] == $val){
                            $v['num'] = $v['num'] + $data['num'];
                            $newadd = false;
                        }
                        $aids[$k] = $v;
                    }
                }
                $daids[] = $val;
                $data['aid'] = implode(',',$daids);
                unset($daids);
            }
            if($newadd){
                $aids[] = $data;
            }
            $olddata['aids'] = serialize($aids);
            if(model('OrderShop')->add_list($olddata)){
                $this->success("添加到购物车成功！");
            }else{
                $this->error("添加到购物车失败！");
            }
        }
    }
    //  处理团购
    public function tuangou(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        //  获取团购信息
        if(empty($getdata['aid'])){
            $this->error("非法访问！");
        }
        // 查询产品信息
        $tuangou = $this->get_shop($getdata['aid']);
        $wxjsapi = $this->get_wxjsapi($this->webdb['www_url'].url('Order/tuangou',array('aid'=>$tuangou['aid'])));
        $this->assign([
           'tuangou' => $tuangou,
           'wxjsapi' => $wxjsapi,
        ]);
        return view();
    }
    //  获取产品详情
    public function get_shop($aid){
        $shopmodel = new \app\common\model\Article();
        $get_shop = $shopmodel->where('aid',$aid)->find();
        $get_shop = $shopmodel->readcont($get_shop);
        return $get_shop;
    }
    //  购物车产品处理
    public function gouwuxue(){
        $gouwuche = model('OrderShop')->where('uid',$this->cxbsuser['uid'])->find();
        $gouwuche = unserialize($gouwuche['aids']);
        if(!empty($gouwuche)){
            foreach ($gouwuche as $k => $v){
                $v['shop'] = $this->get_shop($v['aid']);
                if($v['shop']['kucun'] < $v['num']){
                    $v['num'] = $v['shop']['kucun'];
                }
                $gouwuche[$k] = $v;
            }
        }
        if(request()->isPost()){
            $cxmodel = new cxModel();
            $data = input('post.');
            $data = datatrim($data);
            if(empty($data['shop'])){
                $this->error("请选择商品！");
            }
            //  重新保存购物车
            $oldshop = model('OrderShop')->where('uid',$this->cxbsuser['uid'])->find()->toArray();
            $oldaids = unserialize($oldshop['aids']);
            foreach ($oldaids as $k => $v){
                foreach ($data['shop'] as $val){
                    if($v['aid'] == $val['aid']){
                        unset($oldaids[$k]);
                    }
                }
            }
            $oldshop['aids'] = serialize($oldaids);
            unset($oldaids);
            model('OrderShop')->isUpdate(true)->save($oldshop,['id'=>$oldshop['id']]);
            //  获取产品信息
            $allmoney = $newmoney = '0';
            foreach ($data['shop'] as $k => $v){
                $shop = $this->get_shop($v['aid']);
                $newshop[$k]['aid'] = $v['aid'];
                $newshop[$k]['title'] = $shop['title'];
                $newshop[$k]['picurl'] = $shop['picurl'];
                $newshop[$k]['num'] = $v['num'];
                if($this->cxbsuser['group_id'] == '6'){
                    $newshop[$k]['pricemoney'] = $shop['yinjia'];
                }elseif($this->cxbsuser['group_id'] == '7'){
                    $newshop[$k]['pricemoney'] = $shop['jinjia'];
                }elseif($this->cxbsuser['group_id'] == '8'){
                    $newshop[$k]['pricemoney'] = $shop['pifajia'];
                }else{
                    $newshop[$k]['pricemoney'] = $shop['shichuangjia'];
                }
                $aids[] = $v['aid'];
                $newmoney = bcmul($newshop[$k]['pricemoney'],100);
                $newmoney = bcmul($newmoney,$v['num']);
                $allmoney = $allmoney + $newmoney;
            }
            $oid = 'FOR'.date("Ymd").$this->addoid();
            $data['pricemoney'] = $allmoney;
            $data['shop'] = $newshop;
            $data['mid'] = '100';
            $aids = implode(',',$aids);
            $order = array(
                'oid' => $oid,
                'uid' => $this->cxbsuser['uid'],
                'aid' => $aids,
                'title' => $this->webdb['webname']."购物订单".$oid,
                'allmoney' => $data['pricemoney'],
                'pricemoney' => $data['pricemoney'],
                'playstatus' => '0',
                'mid' => $data['mid'],
                'conf' => serialize($data),
                'addtime' => time(),
                'playtime' => '0',
            );
            if($cxmodel->allowField(true)->save($order)){
                return $this->redirect(url('gouwuche',array('oid'=>$oid)));
            }else{
                $this->error('订单提交失败,请重试');
            }
        }
        $webs = array(
            'title' => "购物车"
        );
        $this->assign([
            'gouwuche' => $gouwuche,
            'webs' => $webs
        ]);
        return view();
    }
    //  购物车结算
    public function gouwuche(){
        $getdata = request()->param();
        if(empty($getdata['oid'])){
            $this->error("请选择商品！");
        }
        $cxmodel = new cxModel();
        $order = $cxmodel->where('oid',$getdata['oid'])->find()->toArray();
        if($order['uid'] !== $this->cxbsuser['uid']){
            $this->error("非法访问！");
        }
        if($order['playstatus'] != '0' && $order['playstatus'] != '4'){
            $this->error("订单已支付！",'User/index');
        }
        $order['conf'] = unserialize($order['conf']);
        $wxjsapi = $this->get_wxjsapi($this->webdb['www_url'].url('Order/gouwuche',array('oid'=>$order['oid'])));
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            //  获取用户信息
            $userdata = model('UserApi')->where('openid',$this->wxuser['openid'])->find();
            $userconf = unserialize($userdata['conf']);
            $data['nickname'] = $userconf['nickname'];
            $data['usertoken'] = $this->wxuser['openid'];
            $data['sex'] = $userconf['sex'];
            $data = array_merge($order['conf'],$data);
            $order['uphone'] = $data['phone'];
            $order['playstatus'] = '4';
            $order['conf'] = serialize($data);
            if($cxmodel->allowField(true)->isUpdate(true)->save($order,['oid'=>$order['oid']])){
                $this->redirect(url('Wxpay/index',array('oid'=>$order['oid'])));
                return view();
            }else{
                $this->error('订单提交失败,请重试');
            }
        }
        $webs = array(
            'title' => "订单结算",
        );
        $this->assign([
            'webs' => $webs,
            'order' => $order,
            'wxjsapi' => $wxjsapi,
        ]);
        return view();
    }
    //  确认收货
    public function shouhuo(){
        $getdata = request()->param();
        if(empty($getdata['oid'])){
            $this->error("非法访问");
        }
        $cxmodel = new cxModel();
        $order = $cxmodel->where('oid',$getdata['oid'])->find()->toArray();
        $order['playstatus'] = '5';
        if($cxmodel->allowField(true)->isUpdate(true)->save($order,['oid'=>$order['oid']])){
            $this->success("确认收货成功！");
        }else{
            $this->error("确认收货失败！");
        }
    }
    // 查看订单详情
    public function get_cha(){
        $getdata = request()->param();
        if(empty($getdata['oid'])){
            $this->error("非法访问！");
        }
        $cxmodel = new cxModel();
        $order = $cxmodel->where('oid',$getdata['oid'])->find()->toArray();
        $order['conf'] = unserialize($order['conf']);
        $order['comment'] = model('Comment')->where('oid',$order['oid'])->where('uid',$this->cxbsuser['uid'])->count();
        $webs = array(
            'title' => "订单详情",
        );
        $this->assign([
            'order' => $order,
            'webs' => $webs,
            'thistime' => time(),
        ]);
        return view();
    }
    public function quxiao(){
        $getdata = request()->param();
        $cxmodel = new cxModel();
        $cxmodel->where('oid',$getdata['oid'])->update(['playstatus' => '0']);
        return true;
    }
    // 查看团购详情
    public function get_tuango(){
        $getdata = request()->param();
        if(empty($getdata['oid'])){
            $this->error("非法访问！");
        }
        $cxmodel = new cxModel();
        $order = $cxmodel->where('oid',$getdata['oid'])->find()->toArray();
        $order['conf'] = unserialize($order['conf']);
        $order['shop'] = $this->get_shop($order['aid']);
        $order['comment'] = model('Comment')->where('oid',$order['oid'])->where('uid',$this->cxbsuser['uid'])->count();
        $webs = array(
            'title' => "团购详情",
        );
        $this->assign([
            'order' => $order,
            'webs' => $webs,
            'thistime' => time(),
        ]);
        return view();
    }
    // 订单评价
    public function get_ping(){
        $getdata = request()->param();
        if(empty($getdata['oid'])){
            $this->error("非法访问！");
        }
        $cxmodel = new cxModel();
        $order = $cxmodel->where('oid',$getdata['oid'])->find()->toArray();
        $order['comment'] = model('Comment')->where('oid',$order['oid'])->where('uid',$this->cxbsuser['uid'])->count();
        if($order['comment'] > 0){
            $this->error("订单已评价！");
        }
        $order['conf'] = unserialize($order['conf']);
        if($order['mid'] == '101'){
            $order['conf']['shop'][] = $this->get_shop($order['aid']);
        }

        $webs = array(
            'title' => "订单评价",
        );
        $this->assign([
            'order' => $order,
            'webs' => $webs,
            'thistime' => time(),
        ]);
        return view();
    }
    //  提交评论
    public function add_ping(){
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            $data['comment'] = $data['cont'];
            $data['addtime'] = time();
            $data['uid'] = $this->cxbsuser['uid'];
            $data['status'] = '1';
            $comfmodel = new Comment();
            if($comfmodel->allowField(true)->save($data)){
                $this->success("评论成功！");
            }else{
                $this->success("评论失败！");
            }
        }
        return;
    }
    //  申请退款
    public function tuikuan(){
        $getdata = request()->param();
        if(empty($getdata['oid'])){
            $this->error("非法访问！");
        }
        $cxmodel = new cxModel();
        $order = $cxmodel->where('oid',$getdata['oid'])->find()->toArray();
        $order['conf'] = unserialize($order['conf']);
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            $order['playstatus'] = '6';
            $order['conf']['tuikuan'] = $data['tuikuan'] * 100;
            $order['conf']['tuikuanshuoming'] = $data['tuikuanshuoming'];
            $order['conf'] = serialize($order['conf']);
            if($cxmodel->allowField(true)->isUpdate(true)->save($order,['oid'=>$order['oid']])){
                $this->success("申请退款成功，我们将在3-5个工作日内给您处理！",url('User/index'));
            }else{
                $this->error("申请退款失败，请重新申请");
            }
        }
        $webs = array(
            'title' => "申请退款",
        );
        $this->assign([
            'order' => $order,
            'webs' => $webs,
            'thistime' => time(),
        ]);
        return view();
    }
    public function get_shoucang(){
        $order = explode(',',$this->cxbsuser['ucollection']);
        foreach ($order as $v){
            $orlist[] = $this->get_shop($v);
        }
        $webs = array(
            'title' => '我的收藏',
        );
        $this->assign([
            'orlist' => $orlist,
            'webs' => $webs
        ]);
        return view();
    }
    // 生成订单编号
    protected function addoid(){
        $numbers = range (1,50);
        shuffle ($numbers);
        $num=8;
        $result = array_slice($numbers,0,$num);
        $result = implode('',$result);
        $newname = '';
        for ( $i = 0; $i < 8; $i++ ) {
            $newname .= substr($result, mt_rand(0, strlen($result) - 1), 1);
        }
        return $newname;
    }
}